<template>
  <div class="update-photo">
    <img class="img" :src="img" ref="imgRef" />
    <div class="toolbar">
      <div @click="$emit('close')">取消</div>
      <div class="confirm" @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserAvatar } from '@/api/user'
export default {
  name: 'UpdatePhoto',
  props: {
    img: {
      type: [Object, String],
      required: true
    }
  },
  components: {},
  data () {
    return {
      cropper: undefined
    }
  },
  created () {},
  mounted () {
    const image = this.$refs.imgRef
    // eslint-disable-next-line no-unused-vars
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      // autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false
    })
  },
  methods: {
    onConfirm () {
      this.cropper.getCroppedCanvas().toBlob(async (blob) => {
        // 生成formdata
        const formData = new FormData()
        formData.append('photo', blob)
        // 提示加载中
        this.$toast.loading({
          message: '加载中',
          forbidClick: true,
          duration: 0
        })
        // 发请求
        const { data: { data: { photo } } } = await updateUserAvatar(formData)
        // 更新父组件数据
        this.$emit('update-photo', photo)
        // 关闭弹层
        this.$emit('close')
        // 提示成功
        this.$toast.success('修改成功')
      })
    }
  },
  watch: {},
  computed: {}
}
</script>

<style lang="less" scoped>
.update-photo {
  background-color: #000;
  height: 100%;
}
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: space-between;
  > div {
    width: 90px;
    height: 90px;
    font-size: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
  }
}
.img {
  display: block;
  max-width: 100%;
}
</style>
